<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Order extends BaseModel
{
    public function businesstime()
    {
        return $this->belongsTo(BusinessTime::class, 'business_time_id');
    }
    public function store()
    {
        return $this->belongsTo(Store::class)->with(['detail:id,store_id,name']);
    }
	// 管理中间表
	public  function ordertogoods()
	{
		return $this->hasMany(OrderToGoods::class);
	}
    // 关联房间
    public function room()
    {
        return $this->belongsTo(Room::class, 'room_id', 'id');
    }
    
	// 关联套餐
    public function setmeal()
    {
        return $this->belongsTo(SetMeal::class);
    }

    public function cashier()
    {
        return $this->hasOne(RecordPay::class)->with(['cahiser_name:id,name']);
    }

    // 访问器
    public function getTimeAttribute($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public function getPriceAttribute($value)
    {
        return $value / 100;
    }
    public function getReceivePriceAttribute($value)
    {
        return $value / 100;
    }
    public function getUncollectedPriceAttribute($value)
    {
        return $value / 100;
    }
    
	/**
	 * 取消超时订单
	 */
    static public function cancelOverTimeOrder()
    {
    	$where = [];
    	$where[] = ['created_at', '<', Carbon::now()->subMinutes(10)];
    	$where[] = ['status', '=', '1'];
    	$orders = self::where($where)->get(['id', 'store_id', 'set_meals_id'])->toArray();
    	
    	if (empty($orders)) {
    		Log::info('没有超时订单要取消');
    		
    		return true;
	    }
    	
//    	foreach($orders as $k => $item) {
//    	    self::returnGoods($item['order_id'], $item['id']);
//    	    self::returnSetMeals($item['order_id'], $item['set_meals_id']);
//    	    self::returnSharpGoods($item['order_id']);
//	    }
    	
        $res = self::where($where)->update(['status' => 5]);
        
        if ($res) {
        	Log::info('已取消超时订单');
        	print_r('没有超时订单需要取消'.PHP_EOL);
        } else {
            Log::info('没有超时订单需要取消');
            print_r('没有超时订单需要取消'.PHP_EOL);
        }
    }
    
    static public function returnGoods($order_id, $store_id)
    {
    	if ($order_id <= 0) {
    	    return false;
	    }
		try {
			$update = self::where(['id' => $order_id])->update(['status' => 5]);
			$goods = new Goods();
			$set_meals_id = self::where(['id'=>$order_id])->value('set_meals_id');
			//套餐商品数量库存的增减
			$goods_meals = SetMealsToGoods::where(['set_meal_id' => $set_meals_id])->get(['goods_id', 'number'])->toArray();
			if ($goods_meals) {
				foreach ($goods_meals as $key => $value) {
					$goods->where('id', $value['goods_id'])->decrement('sell', $value['number']);//销量减少
					$goods->where('id', $value['goods_id'])->increment('stock', $value['number']);//库存增加
				}
			}

			//返回商品库存
			$goods_num = OrderToGoods::where(['order_id' => $order_id])->get(['goods_id', 'number','goods_sku_id'])->toArray();
			if (!empty($goods_num)){
			    $needs = [];
                $record_goods =[];
				foreach ($goods_num as $key => $value) {
				    if (isset($value['goods_sku_id']) && $value['goods_sku_id'] >0){
                        $material = GoodsSkuToMaterial::where('goods_sku_id',$value['goods_sku_id'])->get(['material_id','number'])->toArray();
                        $record_goods[$key]['goods_sku_id'] = $value['goods_sku_id'];
                        GoodsSku::where('id',$value['goods_sku_id'])->increment('stock',$value['number']);
                    }else{
				        $record_goods[$key]['goods_sku_id'] = 0;
                        $material = GoodsToMaterial::where('goods_id',$value['goods_id'])->get(['material_id','number'])->toArray();
                    }
                    foreach ($material as $k =>$v) {
                        if (array_key_exists($material[$k]['material_id'], $needs)) {//组建sku商品的材料和数量
                            $needs[$material[$k]['material_id']] = (int)bcadd($needs[$material[$k]['material_id']], bcmul($value['number'], $material[$k]['number'], 2));
                        } else $needs[$material[$k]['material_id']] = (int)bcmul($value['number'], $material[$k]['number'], 2);
                    }
                    $record_goods[$key]['goods_id'] = $value['goods_id'];
                    $record_goods[$key]['number'] = $value['number'];
                    $record_goods[$key]['description'] = '订单取消';
                    $record_goods[$key]['style'] = 1;
                    $record_goods[$key]['type'] = 1;
                    $record_goods[$key]['created_at'] = date('Y-m-d H:i:s',time());
                    $record_goods[$key]['updated_at'] = date('Y-m-d H:i:s',time());

                    $goods->where('id', $value['goods_id'])->decrement('sell', $value['number']);//销量减少
					$goods->where('id', $value['goods_id'])->increment('stock', $value['number']);//库存增加
				}

                $record_goods_inser = RecordGoods::insert($record_goods);
                if (!$record_goods_inser) {
                    //return $this->showMsg([], '502', '创建订单失败');
                    DB::rollBack();
                }
                $stock = PurchaseToMaterial::getPurchases(array_keys($needs),$sortByDesc = false,(int)$store_id);
                $skuupdate = GoodsSkuToMaterial::reduce($stock, $needs,(int)$store_id, 2);
                if (!$skuupdate){
                    DB::rollBack();
                    //return $this->showMsg([],'1005','该商品库存不足!');
                }
			}

			if (!$update) {
				DB::rollBack();
				//return $this->showMsg([], '1005', '取消失败');
			}
			DB::commit();
			//return $this->showMsg([]);
		}catch (\Exception $e) {
			//事务回滚
			DB::rollBack();
			//return $this->showMsg([], '403', 'Server access denied');
		}
    }
    
    static public function returnSetMeals($order_id, $set_meals_id)
    {
    	$goods = new Goods();
		$set_meals_id = Order::where(['id' => $order_id])->value('set_meals_id');
		if (is_null($set_meals_id)) {
			return false;
		}
		//套餐商品数量库存的增减
		$goods_meals = SetMealsToGoods::where(['set_meal_id' => $set_meals_id])->get(['goods_id', 'number'])->toArray();
		if ($goods_meals) {
			foreach ($goods_meals as $key => $value) {
				$goods->where('id', $value['goods_id'])->decrement('sell', $value['number']);//销量减少
				$goods->where('id', $value['goods_id'])->increment('stock', $value['number']);//库存增加
			}
		}
    }
    
    static public function returnSharpGoods($order_id, $sharp_goods_id = 0)
    {
        // 返回秒杀商品库存
		$sharp_goods_num = OrderToSharp::where(['order_id' => $order_id])->get(['goods_id', 'number','goods_sku_id', 'sharp_goods_id']);
		if (!empty($sharp_goods_num->toArray())) {
			$sku = $sharp_goods_num->whereNotNull('goods_sku_id')->pluck( 'number', 'sharp_goods_id');
			$goods = $sharp_goods_num->whereNull('goods_sku_id')->pluck('number', 'sharp_goods_id');
			if (!empty($sku->toArray())) {
				foreach ($sku->toArray() as $k => $item) {
					SharpToGoods::where('id', $k)->increment('stock', $item);
					SharpToGoods::where('id', $k)->decrement('sell', $item);
				}
			}
			if (!empty($goods->toArray())) {
				foreach ($sku->toArray() as $k => $item) {
					SharpToGoods::where('id', $k)->increment('stock', $item);
					SharpToGoods::where('id', $k)->decrement('sell', $item);
				}
			}
		}
    }
}
